import routes from '../routes/index.js'
import staticMiddleware from 'koa-static'
import { ilog, elog } from './log.js'

class InitManager {
  static app

  static initCore(app) {
    // 入口方法
    InitManager.app = app
    global.ilog = ilog
    global.elog = elog
    InitManager.initLoadRouters()
    InitManager.loadHttpException()
    InitManager.loadConfig()
    InitManager.loadStaticPath()
    InitManager.initModels()
  }

  // 加载全部路由
  static initLoadRouters() {
    InitManager.app.use(routes.routes())
    InitManager.app.use(routes.allowedMethods())
  }

  static loadConfig(path = '') {
    const configPath = path || '../config/index.js' //`${process.cwd()}/src/config/index.js` //注: 在windows上使用绝对路径会报错
    import(configPath).then((config) => {
      global.config = config.default
    })
  }

  static loadHttpException() {
    import('./http-exception.js').then((errors) => {
      global.errs = errors.default
    })
  }

  static loadStaticPath() {
    const staticPath = `${process.cwd()}/public`
    InitManager.app.use(staticMiddleware(staticPath))
  }

  static initModels(path = '') {
    const modelPath = path || `../models/index.js`
    import(modelPath).then((model) => {
      model.initModels()
    })
  }
}

export default InitManager
